package com.foosun.core.util;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.DecimalFormat;

public class ColorUtils {
	
	public static String HEX2RGBA(String hex) {
		String redHex = hex.substring(1,3);
		String greenHex = hex.substring(3,5);
		String blueHex = hex.substring(5,7);
		return ColorUtils.RGB2RGBA(Integer.valueOf(redHex, 16), Integer.valueOf(greenHex, 16), Integer.valueOf(blueHex, 16));
	}

	public static String RGB2RGBA(int r, int g, int b) {
		StringBuffer rgba = new StringBuffer("rgba(");
		int[] arr = new int[]{r, g, b};
		ColorUtils.bouu(arr);
		int min = arr[0];
		BigDecimal alpha = new BigDecimal(255 - min);
		alpha = alpha.setScale(3);
		
		MathContext mc = new MathContext(2, RoundingMode.HALF_DOWN);
		alpha = alpha.divide(new BigDecimal(255), mc);
		
		DecimalFormat form = new DecimalFormat("####0");

		BigDecimal dvalue = new BigDecimal(r-min);
		rgba.append(form.format(dvalue.divide(alpha, mc))).append(",");

		dvalue = new BigDecimal(g-min);
		rgba.append(form.format(dvalue.divide(alpha, mc))).append(",");

		dvalue = new BigDecimal(b-min);
		rgba.append(form.format(dvalue.divide(alpha, mc))).append(",");
		
		rgba.append(alpha).append(")");
		return rgba.toString();
	}
	
	public static String transfer(String orginal, String subs){
		StringBuffer newborn = new StringBuffer();
		String[] arr = orginal.split(",");
		for(int i = 0; i< arr.length -1; i++) {
			newborn.append(arr[i]).append(",");
		}
		newborn.append(subs).append(")");
		return newborn.toString();
	}
	
	public static String transferHEX(String orginalHex, String subs){
		String orginal = ColorUtils.HEX2RGBA(orginalHex);
		return ColorUtils.transfer(orginal, subs);
	}

	public static void bouu(int[] arr) {
		int amr = 0;
		int arrLength = arr.length;

		for (int j = 0; j < arrLength - 1; j++) {

			for (int i = 0; i < arrLength - 1 - j; i++) {

				if (arr[i] > arr[i + 1]) {
					amr = arr[i];
					arr[i] = arr[i + 1];
					arr[i + 1] = amr;
				}
			}
		}
	}
	
	public static void main(String[] args) {
		System.out.println(ColorUtils.HEX2RGBA("#b5b6b6"));
	}
}
